package com.hp.fremarker.beans;

import com.hp.fremarker.web.mvc.Controller;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dongxing
 **/
public class BeanFactory {

    private static Map<Class<?>, Object> classToBean=new ConcurrentHashMap();


    public static Object getBean(Class<?> clazz) {
        return classToBean.get(clazz);

    }
    public static void initBean(List<Class<?>> classes) throws Exception {
        List<Class<?>> toCreate = new ArrayList<>(classes);
        while (!toCreate.isEmpty()) {
            int size = toCreate.size();
            for (int i = 0; i < toCreate.size(); i++) {
                if (finishCreate(toCreate.get(i))) {
                    toCreate.remove(i);
                }
            }
            if (size == toCreate.size()) {
                throw new Exception("cycle dependency!");
            }
        }
    }

    private static boolean finishCreate(Class<?> aClass) throws IllegalAccessException, InstantiationException {

        // 如果不是bean或者controller的注解
        if (!aClass.isAnnotationPresent(Bean.class) && !aClass.isAnnotationPresent(Controller.class)) {
            return true;
        }

        Object bean = aClass.newInstance();
        for (Field declaredField : aClass.getDeclaredFields()) {

            // 添加Autowired的注解
            if (declaredField.isAnnotationPresent(Autowired.class)) {
                Class<?> type = declaredField.getType();
                Object bean1 = BeanFactory.getBean(type);
                if (bean1 == null) {
                    return false;
                }
                declaredField.setAccessible(true);
                declaredField.set(bean, bean1);
            }
        }
        classToBean.put(aClass, bean);
        return true;
    }

}
